package com.tencent.wxcloudrun.controller;

import com.tencent.wxcloudrun.utils.AsposeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tencent.wxcloudrun.config.ApiResponse;
import com.tencent.wxcloudrun.dto.CounterRequest;
import com.tencent.wxcloudrun.model.Counter;
import com.tencent.wxcloudrun.service.CounterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.List;
import java.util.UUID;

/**
 * counter控制器
 */
@RestController

public class CounterController {

  final CounterService counterService;
  final Logger logger;

  public CounterController(@Autowired CounterService counterService) {
    this.counterService = counterService;
    this.logger = LoggerFactory.getLogger(CounterController.class);
  }


  /**
   * 获取当前计数
   * @return API response json
   */
  @GetMapping(value = "/api/count")
  ApiResponse get() {
    logger.info("/api/count get request");
    Optional<Counter> counter = counterService.getCounter(1);
    Integer count = 0;
    if (counter.isPresent()) {
      count = counter.get().getCount();
    }

    return ApiResponse.ok(count);
  }


  /**
   * 更新计数，自增或者清零
   * @param request {@link CounterRequest}
   * @return API response json
   */
  @PostMapping(value = "/api/count")
  ApiResponse create(@RequestBody CounterRequest request) {
    logger.info("/api/count post request, action: {}", request.getAction());

    Optional<Counter> curCounter = counterService.getCounter(1);
    if (request.getAction().equals("inc")) {
      Integer count = 1;
      if (curCounter.isPresent()) {
        count += curCounter.get().getCount();
      }
      Counter counter = new Counter();
      counter.setId(1);
      counter.setCount(count);
      counterService.upsertCount(counter);
      return ApiResponse.ok(count);
    } else if (request.getAction().equals("clear")) {
      if (!curCounter.isPresent()) {
        return ApiResponse.ok(0);
      }
      counterService.clearCount(1);
      return ApiResponse.ok(0);
    } else {
      return ApiResponse.error("参数action错误");
    }
  }

  @PostMapping(value = "/api/convert")
    ApiResponse convert() {
      try {
        AsposeUtil.wordToPdf("d:\\Users\\zkc\\Desktop\\川金房估报（2025）第YG1158号_向华.docx", "d:\\Users\\zkc\\Desktop\\向华3.pdf");
      } catch (Exception e) {
        return ApiResponse.error("转换失败");
      }
      return ApiResponse.ok("success");
  }
  
  /**
   * 将上传的Word文件转换为PDF并返回
   * @param file 上传的Word文件
   * @return 转换后的PDF文件
   */
  @PostMapping(value = "/api/word-to-pdf", produces = MediaType.APPLICATION_PDF_VALUE)
  ResponseEntity<?> convertWordToPdf(@RequestParam("file") MultipartFile file) {
    logger.info("/api/word-to-pdf post request");
    
    try {
      // 检查文件是否为空
      if (file.isEmpty()) {
        String errorJson = "{\"code\":-1,\"errorMsg\":\"文件不能为空\",\"data\":{}}";
        return ResponseEntity.badRequest()
            .header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
            .body(errorJson.getBytes("UTF-8"));
      }
      
      // 检查文件类型
      String originalFilename = file.getOriginalFilename();
      if (originalFilename == null || 
          (!originalFilename.toLowerCase().endsWith(".doc") && 
           !originalFilename.toLowerCase().endsWith(".docx"))) {
        String errorJson = "{\"code\":-1,\"errorMsg\":\"只支持.doc或.docx文件\",\"data\":{}}";
        return ResponseEntity.badRequest()
            .header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
            .body(errorJson.getBytes("UTF-8"));
      }
      
      // 创建临时文件
      String tempDir = System.getProperty("java.io.tmpdir");
      String uniqueId = UUID.randomUUID().toString();
      File wordFile = new File(tempDir, uniqueId + "_" + originalFilename);
      File pdfFile = new File(tempDir, uniqueId + "_" + 
                  originalFilename.substring(0, originalFilename.lastIndexOf(".")) + ".pdf");
      
      // 保存上传的文件
      file.transferTo(wordFile);
      
      // 转换Word为PDF
      boolean success = AsposeUtil.wordToPdf(wordFile.getAbsolutePath(), pdfFile.getAbsolutePath());
      
      if (!success) {
        // 清理临时文件
        wordFile.delete();
        pdfFile.delete();
        String errorJson = "{\"code\":-1,\"errorMsg\":\"文件转换失败\",\"data\":{}}";
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
            .body(errorJson.getBytes("UTF-8"));
      }
      
      // 读取生成的PDF文件
      Path pdfPath = Paths.get(pdfFile.getAbsolutePath());
      byte[] pdfBytes = Files.readAllBytes(pdfPath);
      
      // 清理临时文件
      wordFile.delete();
      pdfFile.delete();
      
      // 设置响应头
      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.APPLICATION_PDF);
      headers.setContentDispositionFormData("attachment", 
          originalFilename.substring(0, originalFilename.lastIndexOf(".")) + ".pdf");
      
      return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK);
      
    } catch (Exception e) {
      logger.error("Word转PDF过程中发生错误: ", e);
      try {
        String errorJson = "{\"code\":-1,\"errorMsg\":\"文件转换过程中发生错误: " + e.getMessage() + "\",\"data\":{}}";
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
            .body(errorJson.getBytes("UTF-8"));
      } catch (Exception ex) {
        logger.error("构建错误响应时发生异常: ", ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new byte[0]);
      }
    }
  }
  
}